package com.jiajia.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiajia.server.config.security.compontent.JwtTokenUtils;
import com.jiajia.server.mapper.AdminMapper;
import com.jiajia.server.mapper.AdminRoleMapper;
import com.jiajia.server.mapper.RoleMapper;
import com.jiajia.server.pojo.*;
import com.jiajia.server.service.IAdminService;
import com.jiajia.server.utils.AdminUtils;
import com.jiajia.server.utils.FastDfsUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jiajia
 * @since 2021-08-10
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
        @Autowired
        private UserDetailsService userDetailsService;
        @Autowired
        private PasswordEncoder passwordEncoder;
        @Autowired
        private JwtTokenUtils jwtTokenUtils;
        @Autowired
        private RoleMapper roleMapper;
        @Autowired
        private AdminRoleMapper adminRoleMapper;

        @Autowired
        private AdminMapper adminMapper;

        @Value("${jwt.tokenHead}")
        private String tokenHead;

    /**
     * 登录之后返回token
     * @param adminLoginParm
     * @param request
     * @return
     */
    @Override
    public RespBean login(AdminLoginParm adminLoginParm, HttpServletRequest request) {
                //判断验证码是否正确
        String code = (String) request.getSession().getAttribute("captcha");
        if (adminLoginParm.getCode()==null || !adminLoginParm.getCode().equalsIgnoreCase(code)){
            return RespBean.error("验证码错误");
        }
                //登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(adminLoginParm.getUsername());
        if (userDetails==null||!passwordEncoder.matches(adminLoginParm.getPassword(),userDetails.getPassword())){
                return  RespBean.error("用户名或密码不正确");
            }
            if (!userDetails.isEnabled()){
                return RespBean.error("账号被禁用，请联系管理员！");
            }
            //更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken =
                                                                            new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

            //生成token
            String token = jwtTokenUtils.generateToken(userDetails);

            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            map.put("tokenHead",tokenHead);

        return RespBean.success("登录成功",map);
    }


    /**
     * 返回登陆信息
     * @param username
     * @return
     */

    @Override
    public Admin getAdminByUserName(String username) {
        return  adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",username).eq("enabled",true));
    }

    /**
     * 根据用户id查询角色
     * @return
     */
    @Override
    public List<Role> getRole(Integer adminId) {
        return  roleMapper.getRole(adminId);
    }

    /**
     * 查询操作员
     * @param keyword
     * @return
     */

    @Override
    public List<Admin> getAllAdmin(String keyword) {

        Integer adminId = AdminUtils.getAdmin().getId();
        return adminMapper.getAllAdmin(adminId,keyword);
    }

    /**
     * 更新操作员角色
     * @param id
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public RespBean updateAdminRole(Integer id, Integer[] ids) {
        //先全部删除
        adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("aid",id));
        Integer integer = adminRoleMapper.updateAdminRole(id, ids);
        if (integer  == ids.length){
            return RespBean.success("更新成功");
        }
        return  RespBean.error("更新失败");
    }

    /**
     * 更改密码
     * @param oldPass
     * @param pass
     * @param adminId
     * @return
     */
    @Override
    public RespBean updatePassWord(String oldPass, String pass, Integer adminId) {
        //根据用户id查出用户
        Admin admin = adminMapper.selectById(adminId);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        System.out.println("加密密码为："+encoder.encode("123"));
        //是否和老密码匹配
            if (encoder.matches(oldPass,admin.getPassword())){
                //更改密码
                admin.setPassword(encoder.encode(pass));
                int update = adminMapper.updateById(admin);
                if (update==1){
                    return RespBean.success("更改成功");
                }
            }

        return RespBean.error("更改失败");
    }

    /**
     * 更新用户头像
     * @param url
     * @param id
     * @param authentication
     * @return
     */

    @Override
    public RespBean updateUserFace(String url, Integer id, Authentication authentication) {
        Admin admin = adminMapper.selectById(id);
        admin.setUserFace(url);
        int update = adminMapper.updateById(admin);
        if (update==1){
            Admin principal = (Admin) authentication.getPrincipal();
            principal.setUserFace(url);
            SecurityContextHolder.getContext().setAuthentication(
                    new UsernamePasswordAuthenticationToken(admin,null,authentication.getAuthorities()));
            return RespBean.success("更新成功",url);
        }
        return RespBean.error("更新失败");
    }


}
